from simu_common import Cbid, getStepOptRevenue, bids_key
from simu_rng2 import get_uniform, get_poisson
from pylab import grid, show, plot

#
#   Try out the R0 with step simulation
#

g_arr_rate = 5
g_periods = 50

def get_arrivals(rate, periods):
    '''
        Output: a serial of arrival bids numbers
    '''
    return get_poisson(rate, periods)
    
def get_bids(num):
    '''
        Output: a serial of arrival bids with given number
    '''
    bids = []
    vp = get_uniform(num)
    vs = get_uniform(num)
    for i in xrange(0, num):
        bids.append(Cbid(vp[i], vs[i]))
        
    return bids

def get_bids_flow(rate, T):
    arrs = get_arrivals(rate, T)
    num = sum(arrs)
    bids = get_bids(num)
    return arrs, bids
    
def exp_opt_revenue(v_arr, v_bids, k, tao, r0, y0, C):
    '''
    '''
    revenue = 0.0
    T = len(v_arr)
    bids = []
    cur_bid = 0
    for a in v_arr:
        for i in xrange(0, a):
            bids.append(v_bids[cur_bid])
            cur_bid = cur_bid + 1
        
        bids.sort(key=bids_key, reverse=True)
        revenue = revenue + getStepOptRevenue(bids, k, tao, r0, y0, C)
  
    return revenue/T
    
def test_r0(arr_rate, periods, step, k, tao, y0, C):
    '''
    '''
    rs = []
    rvs = []
    r0 = step
    while r0 < 1:
        rs.append(r0)
        r0 = r0 + step
    
    v_arrs, v_bids = get_bids_flow(arr_rate, periods)
    
    for r in rs:
        rvs.append(exp_opt_revenue(v_arrs, v_bids, k, tao, r, y0, C))
    
    return rs, rvs
    
if __name__ == "__main__":
    
    rs, rvs = test_r0(g_arr_rate, g_periods, step=0.01, k=8, tao=1.4, y0=1, C=0.01)
    grid(True)
    plot(rs, rvs)
    show()